package src.twice;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class MyZip {

    private void zip(String zipFileName, File inputFile){
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
            zip(out,inputFile,"");
            System.out.println("压缩中。。。");
            out.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void zip(ZipOutputStream out,File f,String base){
        if(f.isDirectory()){
            File[] fl = f.listFiles();
            try {
                out.putNextEntry(new ZipEntry(base+"/"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            base = base.length()==0 ? "" : base+"/";
            for (int i = 0; i < fl.length; i++) {
                zip(out,fl[i],base+fl[i]);
            }
        }else {
            try {
                out.putNextEntry(new ZipEntry(base));
                FileInputStream in = new FileInputStream(f);
                int b;
                System.out.println("base:"+base);
                while ((b=in.read())!=-1){
                    out.write(b);
                }
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }


        }

    }

    public static void main(String[] args) {
        MyZip book = new MyZip();
        book.zip("C:\\Users\\22528\\Desktop\\text.zip",new File("C:\\Users\\22528\\Desktop\\新建文件夹"));
        System.out.println("压缩完成");
    }
}
